import pymysql
from config import mysql_config

def get_mysql_connection():
    """
    获取MySQL数据库连接
    """
    try:
        connection = pymysql.connect(
            host=mysql_config["host"],
            port=mysql_config["port"],
            user=mysql_config["user"],
            password=mysql_config["password"],
            database=mysql_config["database"],
            charset=mysql_config["charset"]
        )
        return connection
    except Exception as e:
        print(f"MySQL连接错误: {e}")
        return None

def execute_query(sql, params=None):
    """
    执行查询SQL语句
    """
    connection = get_mysql_connection()
    if connection:
        try:
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute(sql, params)
                result = cursor.fetchall()
                return result
        except Exception as e:
            print(f"查询执行错误: {e}")
            return None
        finally:
            connection.close()
    return None

def execute_update(sql, params=None):
    """
    执行更新SQL语句（插入、更新、删除）
    """
    connection = get_mysql_connection()
    if connection:
        try:
            with connection.cursor() as cursor:
                affected_rows = cursor.execute(sql, params)
                connection.commit()
                return affected_rows
        except Exception as e:
            connection.rollback()
            print(f"更新执行错误: {e}")
            return 0
        finally:
            connection.close()
    return 0

def execute_many(sql, params_list):
    """
    批量执行SQL语句
    """
    connection = get_mysql_connection()
    if connection:
        try:
            with connection.cursor() as cursor:
                affected_rows = cursor.executemany(sql, params_list)
                connection.commit()
                return affected_rows
        except Exception as e:
            connection.rollback()
            print(f"批量执行错误: {e}")
            return 0
        finally:
            connection.close()
    return 0

# 测试连接
if __name__ == "__main__":
    conn = get_mysql_connection()
    if conn:
        print("MySQL连接成功!")
        conn.close()
    else:
        print("MySQL连接失败!") 